package cn.tedu.pdfamily.product.repo.impl;

import cn.tedu.pdfamily.product.pojo.vo.RoleListItemVO;
import cn.tedu.pdfamily.product.pojo.vo.RoleStandardVO;
import cn.tedu.pdfamily.product.repo.IRoleRedisRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Repository;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 处理用户缓存的数据访问实现类
 *
 * @author java@tedu.cn
 * @version 0.0.1
 */
@Slf4j
@Repository
public class RoleRedisRepositoryImpl implements IRoleRedisRepository {
    @Autowired
    private RedisTemplate<String, Serializable> redisTemplate;

    public RoleRedisRepositoryImpl(){
        log.debug("创建处理缓存的数据访问对象：RoleRedisRepositoryImpl");
    }

    @Override
    public void save(RoleStandardVO roleStandardVO) {
        String key = ROLE_ITEM_KEY_PREFIX + roleStandardVO.getId();
        redisTemplate.opsForSet().add(ROLE_ITEM_KEYS_KEY, key);
        redisTemplate.opsForValue().set(key, roleStandardVO);
    }

    @Override
    public void save(List<RoleListItemVO> roles) {
        String key = ROLE_LIST_KEY;
        ListOperations<String, Serializable> ops = redisTemplate.opsForList();
        for (RoleListItemVO role : roles) {
            ops.rightPush(key, role);
        }
    }

    @Override
    public Long deleteAll() {
        // 获取到所有item的key
        Set<Serializable> members = redisTemplate
                .opsForSet().members(ROLE_ITEM_KEYS_KEY);
        Set<String> keys = new HashSet<>();
        for (Serializable member : members) {
            keys.add((String) member);
        }
        // 将List和保存Key的Set的Key也添加到集合中
        keys.add(ROLE_LIST_KEY);
        keys.add(ROLE_ITEM_KEYS_KEY);
        return redisTemplate.delete(keys);
    }

    @Override
    public RoleStandardVO get(Long id) {
        Serializable serializable = redisTemplate
                .opsForValue().get(ROLE_ITEM_KEY_PREFIX + id);
        RoleStandardVO roleStandardVO = null;
        if (serializable != null) {
            if (serializable instanceof RoleStandardVO) {
                roleStandardVO = (RoleStandardVO) serializable;
            }
        }
        return roleStandardVO;
    }

    @Override
    public List<RoleListItemVO> list() {
        long start = 0;
        long end = -1;
        return list(start, end);
    }

    @Override
    public List<RoleListItemVO> list(long start, long end) {
        String key = ROLE_LIST_KEY;
        ListOperations<String, Serializable> ops = redisTemplate.opsForList();
        List<Serializable> list = ops.range(key, start, end);
        List<RoleListItemVO> roles = new ArrayList<>();
        for (Serializable item : list) {
            roles.add((RoleListItemVO) item);
        }
        return roles;
    }
}
